<?php

namespace Controller\Admin;

use Daiyong\Db as db;

class Admin extends Common {
    private $model;
    public function __construct() {
        parent::__construct();
        $this->model = new \Model\Admin();
    }
    public function info() {
        $get = @array(
            'id' => (int)$_GET['id']
        );
        $data = $this->model->find(['id' => $get['id']]);

        $this->success($data);
    }
    private function listSearch() {
        $query = @array(
            'search|like' => '%' . $_GET['search'] . '%',
            'gid' => is_numeric($_GET['gid']) ? $_GET['gid'] : '',
            'date_create|>=' => $_GET['date_begin'],
            'date_create|<=' => $_GET['date_end']
        );
        $orderBy = $this->sqlOrderBy(['id', 'time_create']); //设置允许用户手动排序的字段
        return [$query, $orderBy];
    }
    public function list() {
        list($query, $orderBy) = $this->listSearch();
        $list = $this->model->findAll($query, $orderBy, $this->sqlLimit());
        //查询总数
        $total = (int)db::find($this->model->table . '|count("id")', $this->model->findClear($query));

        $this->success([
            'list' => $list,
            'total' => $total
        ]);
    }
    public function listExport() {
        list($query, $orderBy) = $this->listSearch();
        $filePath = $this->model->export($query, $orderBy);
        $this->download($filePath);
    }
    public function edit() {
        $data = @array(
            'id' => (int)$_POST['id'],
            'gid' => (int)$_POST['gid'],
            'username' => $_POST['username'],
            'phone' => $_POST['phone'],
            'mail' => $_POST['mail'],
            'password' => $_POST['password'],
            'nickname' => $_POST['nickname'],
            'head' => $_POST['head'],
        );
        if ($data['id'] && !$data['password']) unset($data['password']);
        $return = $this->model->edit($data);
        if (is_array($return)) {
            $this->error($return['message']);
        }
        if ($data['id']) {
            if ($return) $this->success('修改成功');
            else $this->echo(2, '未进行任何变更');
        } else {
            $this->result($return, '新增成功', '新增失败');
        }
    }
    public function delete() {
        $post = @array(
            'ids' => array_map('intval', toArray($_POST['ids']))
        );
        $returns = array();
        foreach ($post['ids'] as $v) {
            $returns[] = array(
                'key' => $v,
                'option' => '删除',
                'return' => $this->model->delete(['id' => $v], $this->loginUser)
            );
        }
        if (!$returns) $this->error('删除失败');
        $this->resultArray($returns);
    }
}
